<?php
class openAction extends baseAction{

	public function index(){
		if($_GET['code']!=''){
			//获取access_token;
			 //echo "get acces";
			 $code = $_REQUEST['code'];   //通过访问https://oauth.taobao.com/authorize获取code
			 $grant_type = 'authorization_code';
			 $redirect_uri = 'http://m.wantujie.com/?m=open';  //此处回调url要和后台设置的回调url相同
			 $client_id = '12587554';//自己的APPKEY
			 $client_secret = '744986c5b0db2bd869c4f22e9ea2b114';//自己的appsecret
			 $client_id = C('APP_KEY');//自己的APPKEY
			 $client_secret = C('APP_SECRET');//自己的appsecret
			
			 //请求参数
			 $postfields= array( 'grant_type'     => $grant_type,
								 'client_id'     => $client_id,
								 'client_secret' => $client_secret,
								 'code'          => $code,
								 'redirect_uri'  => $redirect_uri,
								 'view'          => 'wap'
			 );
			 
			$url = 'https://oauth.taobao.com/token';
			try{
				$token = json_decode(curl($url,$postfields));
			}catch(Exception $e){
				echo "出错了！！！！";
				return ;
			}
			$access_token = $token->access_token;
			
			$userName = urldecode($token->taobao_user_nick);
			
			Cookie('userName',$userName);
			$users = D("ju_users");
			$u = $users->where("user_name='".$userName."'")->find();
			if(!$u){
				$newUser = array(
					"user_name"=>$userName,
					"points"=>0,
					"access_token"=>$access_token
				);
				$users->add($newUser);
			}
			//获取买家信息；
			//
			$c = $this->taobao_client();
			$req = $c->load_api('UserBuyerGetRequest');
			$req->setFields("nick,avatar");
			$resp = $c->execute($req, $access_token);
			$resp = object_array($resp);
			
			
			$id = $users->where("user_name='".$userName."'")->find();
			$id = $id['id'];
			$data['id'] = $id;
			$data['imgs'] = $resp['user']['avatar'];
			$data['user_name'] = $resp['user']['nick'];
			$data['access_token'] = $token->access_token;
			
			//print_r($data);
			$users->create();
			$users->save($data);
			//echo $users->getLastSql();
			//exit();
			header("Location://m.wantujie.com");
			//echo $users->getLastSql();
		}else{
			echo "出错啦！~~";
		}
		
	}
	public function login(){
		header("Location:".'https://oauth.taobao.com/authorize?&client_id=21301132&view=wap&response_type=code&scope=item&redirect_uri=http%3A%2F%2Fm.wantujie.com%2F?m=open');
	}
}
?>
